import './less/index.less'
import React, { FC, useEffect, useState } from 'react'
import ProLayout, {
  MenuDataItem,
  BasicLayoutProps as ProLayoutProps,
  BasicLayoutProps,
  ProBreadcrumb,
  ProSettings,
} from '@ant-design/pro-layout'
import { BlankList, LoginPath, ProjectName } from '@/common/constants'
import HeaderHelper from './Header/helper'
import Hamburger from './Header/hamburger'
import { useHistory, useLocation, useModel } from 'umi'
import { TransitionGroup, CSSTransition } from 'react-transition-group'
import router, { rootRoutes } from '@/router'
import UserLayout from './UserLayout'
import BlankLayout from './BlankLayout'
import TagsView from './TagsView'
import { Divider } from 'antd'
import AppSettings from './Settings'
import Source from './source'

export interface LayoutProps {
  breadcrumbNameMap?: {
    [path: string]: MenuDataItem
  }
  location?: ProLayoutProps['location']
  route?: ProLayoutProps['route']
  children: React.ReactElement
}

const ANIMATION_MAP: any = {
  PUSH: 'forward',
  POP: 'back',
}

const BasicLayout: FC<LayoutProps> = (props) => {
  const { children } = props
  const history = useHistory()
  const location = useLocation()
  const { pathname } = location
  const [collapsed, setCollapsed] = useState(false)
  const [subTitle, setSubTitle] = useState(rootRoutes[0].name)
  const [routes, setRoutes] = useState<MenuDataItem[]>()
  const [settings, setSetting] = useState<Partial<ProSettings> | undefined>()
  const { addTag } = useModel('tagsView')
  const currentPath = '/home'

  useEffect(() => {
    setCurrentRouter(`/${pathname.split('/')[1]}`)
  }, [pathname])

  const getCurrentMenu = (routers: MenuDataItem[], path: string) => {
    return routers.find((item: MenuDataItem) => item.path === path)
  }

  const setCurrentRouter = (path: string = currentPath) => {
    const cur = getCurrentMenu(router, path)
    cur && setRoutes(cur?.routes)
  }

  if (pathname === LoginPath) {
    return <UserLayout>{children}</UserLayout>
  }

  if (BlankList.includes(pathname)) {
    return <BlankLayout>{children}</BlankLayout>
  }

  const proProps: BasicLayoutProps = {
    location: {
      pathname,
    },
    title: false,
    logo: false,
    collapsedButtonRender: false,
    collapsed: false,
    route: {
      routes: rootRoutes,
    },
    headerRender: false,
    disableContentMargin: true,
    className: 'app-wrap-prop-layout',
    menuProps: {
      // style: { width: '68px' },
      // className: 'app-prop-layout-menu',
      onClick: ({ item, key }: any) => {
        const title = item?.props.elementRef.current.innerText

        setSubTitle(title)
        setCurrentRouter(key)
        history.push(key)
      },
    },
  }

  const menuProProps: BasicLayoutProps = {
    title: ProjectName,
    navTheme: 'light',
    collapsed,
    fixSiderbar: true,
    collapsedButtonRender: false,
    className: 'app-main-basic-layout',
    menuHeaderRender: () => <div className="app-extra-menu">{ProjectName.replace(/\s+/g, '')}</div>,
    headerContentRender: () => (
      <div className="app-header-crumb">
        <Hamburger collapsed={collapsed} setCollapsed={setCollapsed} />
        <ProBreadcrumb className="app-breadcrumb" />
      </div>
    ),
    menuExtraRender: () => <Divider>{subTitle}</Divider>,
    breadcrumbRender: (routers = []) => [
      {
        path: '/',
        breadcrumbName: '主页',
      },
      ...routers,
    ],
    onCollapse: setCollapsed,
    location: {
      pathname,
    },
    route: {
      routes,
    },
    headerHeight: 58,
    rightContentRender: HeaderHelper,
    menuProps: {
      onClick: ({ item, key }: any) => {
        const title = item?.props.elementRef.current.innerText
        const tag = { title, path: key }

        addTag(tag)
        history.push(key)
      },
    },
  }

  return (
    <div id="app-basic-pro-layout" className="app-basic-container" style={{ height: '100vh' }}>
      <ProLayout {...proProps}>
        <ProLayout {...menuProProps}>
          <TagsView />
          <AppSettings settings={settings} setSetting={setSetting} pathname={pathname} />
          <div className="app-children-container">
            <TransitionGroup
              childFactory={(child: React.FunctionComponentElement<{ classNames: any }>) =>
                React.cloneElement(child, { classNames: ANIMATION_MAP[history.action] })
              }
            >
              <CSSTransition key={location.pathname} timeout={300}>
                {children}
              </CSSTransition>
            </TransitionGroup>
          </div>
          <Source />
        </ProLayout>
      </ProLayout>
    </div>
  )
}

export default BasicLayout
